package org.mg.engine.core;

import org.mg.engine.Instruct;
import org.mg.engine.InstructAbstract;
import org.mg.engine.InstructFactory;
import org.msg.commons.InstructUtils;
import org.msg.commons.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.MessageFormat;

/**
 * Create by bo.chen in 2018/10/9 0:21
 */
public class MgSession extends SessionAbstract {

    public MgSession(Socket socket) {
        this.socket = socket;
        this.init();
    }

    private void init() {
        try {
            listen();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Socket getSocket() {
        return this.socket;
    }

    @Override
    public void println(String message) throws IOException {
        try {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println(message);
        } catch (Exception e) {
            Logger.log("发送消息失败");
        }
    }

    @Override
    public void println(String key,String message) throws IOException {
        try {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println(MessageFormat.format("{1} {2}",key,message));
        } catch (Exception e) {
            Logger.log("发送消息失败");
        }
    }


    @Override
    public String listen() throws IOException {
        while(true){
            String message = new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();
            if(!InstructUtils.doub(message.trim())) {
                Instruct instruct = InstructFactory.getBean(message.trim());
                instruct.init(this).execute(null);
            } else {
                String cmd = InstructUtils.getInstruct(message);
                Instruct instruct = InstructFactory.getBean(cmd.trim());
                String params = InstructUtils.getParams(message);
                instruct.init(this).execute(params.trim());
            }
        }
    }
}
